package net.xo68.destiny.starter.worker.handler.impl;

import lombok.extern.slf4j.Slf4j;
import net.xo68.destiny.contract.domain.job.TriggerParameter;
import net.xo68.destiny.core.rocksdb.RocksDBStorage;
import net.xo68.destiny.starter.worker.SchedulerWorkerProperties;
import net.xo68.destiny.starter.worker.enums.JobLocalConfigType;
import net.xo68.destiny.starter.worker.handler.JobLocalConfigStore;
import net.xo68.destiny.starter.worker.handler.JobLocalConfigStoreFactory;
import net.xo68.destiny.starter.worker.logger.JobLogger;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.SmartInitializingSingleton;

/**
 * 本地配置存储工厂实现
 * @author wuxie
 * @version 2020-22-24
 */
@Slf4j
public class JobLocalConfigStoreFactoryImpl implements JobLocalConfigStoreFactory, SmartInitializingSingleton, DisposableBean {

    private final SchedulerWorkerProperties workerProperties;
    private final RocksDBStorage dbStorage;

    public JobLocalConfigStoreFactoryImpl(SchedulerWorkerProperties workerProperties) {
        this.workerProperties = workerProperties;
        this.dbStorage=new RocksDBStorage(workerProperties.sourcePath()+"/localconfigdb",true,true);
    }

    @Override
    public JobLocalConfigStore create(JobLocalConfigType localConfigType, JobLogger jobLogger, TriggerParameter triggerParameter, String sourceSuffix) {
        return new JobLocalConfigStoreImpl(workerProperties,localConfigType,jobLogger,triggerParameter,sourceSuffix,this.dbStorage);
    }

    @Override
    public JobLocalConfigStore create(JobLocalConfigType localConfigType, JobLogger jobLogger, TriggerParameter triggerParameter, String sourceSuffix, String configSuffix) {
        return new JobLocalConfigStoreImpl(workerProperties,localConfigType,jobLogger,triggerParameter,sourceSuffix,this.dbStorage,configSuffix);
    }

    @Override
    public void destroy() throws Exception {
        log.debug("销毁 任务扩展字段配置本地缓存的 rockdb");
        try {
            dbStorage.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void afterSingletonsInstantiated() {
        log.debug("初始化rockdb");
        dbStorage.init();
    }
}
